﻿using SameGame.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SameGame.Presentation.Presenters
{
	internal class BoardPresenter : IBoardPresenter
	{
		IBoardView _boardView;
		IBoard _board;

		internal BoardPresenter(IBoard board)
		{
			_board = board;
			_board.BoardInited += _board_BoardInited;
		}

		void _board_BoardInited(object sender, EventArgs e)
		{
			if (_boardView != null)
			{
				InitView();
			}
		}

		public IBoardView View
		{
			get
			{
				return _boardView;
			}
			set
			{
				_boardView = value;
				InitView();
			}
		}

		private void InitView()
		{
			_boardView.DeleteBalls();

			_boardView.Columns = _board.Width;
			_boardView.Rows = _board.Height;

			if (_board.getAllItems() != null)
			{
				foreach (CItem item in _board.getAllItems())
				{
					_boardView.ShowItem(item.Location.x, item.Location.y, item._color);
				}
			}
		}

		public void Highlight(int column, int row)
		{
			if (_board.Highlight(column, row)) {

				CFrame frame = _board.getLastFrame();
				_boardView.ClearHighlights();

				foreach (CItem ball in frame.getHighlighted()) {
					_boardView.Highlight(ball.Location.x, ball.Location.y, true);
				}

				_boardView.ShowAvailableScore(frame.Score);
			}
		}

		public void Remove(int column, int row)
		{
			if (_board.Remove(column, row)) {

				CFrame frame = _board.getLastFrame();

				foreach (CItem ball in frame.getHighlighted()) {
					_boardView.RemoveBall(ball.Location.x, ball.Location.y);
				}

				foreach (CItem ball in frame.getReplaced()) {
					_boardView.MoveBall(ball.PreviousLocation.x, ball.PreviousLocation.y, ball.Location.x, ball.Location.y);
				}
			}
		}
	}
}
